function [C, gamma] = gridParameter(X,Y,params)
% calculate best parameter using RBF kernel
% function x = gridParameter(X,Y,params)
% params is matrix with form 
% | xmin  xmax  dx |
% | ymim  ymax  dy |

fprintf('finding optimal C and gamma\n');
global Standardize showGraph;
kfold = 5;
% showGraph = false;
rng(1);
N = size(X,1);
c = cvpartition(N,'KFold',kfold);

if(nargin < 3)
% loose grid
    xmin = -5;xmax = 15; dx = 2;
    ymin = -15; ymax = 3; dy = 2;
else
    xmin = params(1,1);xmax = params(1,2); dx = params(1,3);
    ymin = params(2,1);ymax = params(2,2); dy = params(2,3);
end

nx = (xmax - xmin)/dx +1;
ny = (ymax - ymin)/dy +1;
fres = zeros(nx,ny);

index1 = 1;
for i = xmin: dx: xmax
    index2 = 1;
    for  j = ymin: dy : ymax
        C = 2.^i;
        scale = 2.^j;
        fres(index1,index2)= kfoldLoss(fitcsvm(X,Y,'CVPartition',c,...
                'KernelFunction','rbf','BoxConstraint',C,...
                'KernelScale',scale,'Standardize',Standardize));
        index2 = index2+1;
    end
    index1 = index1+1;    
end

minV = min(min(fres));
[row, col] = find(fres == minV);
C = 2.^(dx*(row-1)+xmin);
gamma = 2.^(dy*(col-1)+ymin);
fprintf('min CV %2.3f\n',minV);
fprintf('C = %f,gamma = %f \n',C,gamma);

if(showGraph)
    contour(xmin:dx:xmax, ymin:dy:ymax,fres','showtext','on');
end

end